package com.gxc.mall.common.util;

import com.gxc.mall.common.enums.JwtEnum;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author GongXincheng
 * @since 2019-09-04 12:59
 */
@Data
@Slf4j
@Component
@ConfigurationProperties(prefix = "gxc.mall.auth")
public class JwtUtil {

    private Long ttl;
    private List<String> token = new ArrayList<>();


    /**
     * 解析token.
     *
     * @param token token
     * @return Claims
     */
    public Claims parseJwt(String token) {
        try {
            Claims claims = Jwts.parser()
                    .setSigningKey(JwtEnum.TOKEN_SALT.getCode())
                    .parseClaimsJws(token)
                    .getBody();
            log.info("token解析成功：{}", claims.toString());
            return claims;
        } catch (ExpiredJwtException e) {
            throw new RuntimeException("token已过期, 请重新获取");
        } catch (Exception e) {
            throw new RuntimeException("令牌不正确");
        }
    }
}
